package com.kang.mavenweb.action;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kang.mavenweb.domain.Book;
import com.kang.mavenweb.domain.User;
import com.kang.mavenweb.service.IBookService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@ParentPackage("struts-default")
public class BookAction extends ActionSupport {

    @Autowired
    private IBookService bookService;
//
    @Action(value = "book")
    public String bookList() throws IOException {
        ServletActionContext.getRequest ().setCharacterEncoding ("utf-8");
        ServletActionContext.getResponse ().setCharacterEncoding ("utf-8");
        User user = (User) ServletActionContext.getRequest ( ).getSession ( ).getAttribute ("user");
        Integer id = user.getId ( );
        List<Book> byUser = bookService.findByUser (id);
        System.out.println (id+"***********" );
        System.out.println (byUser+"*****************" );
        ArrayList<Object> results = new ArrayList<> ( );
        results.add (byUser);
        results.add (user.getUsername ( ));
        //对json数据进行过滤,并且取消循环引用
        PropertyFilter propertyFilter=new PropertyFilter ( ) {
            @Override
            public boolean apply(Object o, String fieldName, Object o1) {
                if("us".equalsIgnoreCase (fieldName)){
                    return false;
                }

                return true;
            }
        };

        ServletActionContext.getResponse ().getWriter ().write (JSONArray.toJSONString (results,propertyFilter, SerializerFeature.DisableCircularReferenceDetect));
        return null;
    }
}
